import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import '../../services/auth_service.dart'; 
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import 'package:provider/provider.dart';
import '/models/checkinObj.dart';
import '../system/fontsize_provider.dart';
import '../../utils/message_box.dart';

class CheckinDetailScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;
  
  const CheckinDetailScreen({super.key, required this.jsonData});

  @override
  _CheckinDetailScreenState createState() => _CheckinDetailScreenState();
}

class _CheckinDetailScreenState extends State<CheckinDetailScreen> with WidgetsBindingObserver {
  Checkinobj? _checkinobj;
  bool _isLoading = false;
  bool _isReadOnly = false;
  bool _hasShipmentCode = true;

  var id;
  var order;
  var warehouse;
  final _poController = TextEditingController();
  final _shipmentController = TextEditingController();
  final _datetimeController = TextEditingController();
  final _carrierController = TextEditingController();
  final _proController = TextEditingController();
  final _bolController = TextEditingController();
  final _sealController = TextEditingController();
  final _trailerController = TextEditingController();
  final _scacController = TextEditingController();
  final _containersController = TextEditingController();
  final _itemsController = TextEditingController();
  int? warehouseId;

  // 焦点节点
  final _poFocusNode = FocusNode();
  final _shipmentFocusNode = FocusNode();
  final _datetimeFocusNode = FocusNode();
  final _carrierFocusNode = FocusNode();
  final _proFocusNode = FocusNode();
  final _bolFocusNode = FocusNode();
  final _sealFocusNode = FocusNode();
  final _trailerFocusNode = FocusNode();
  final _scacFocusNode = FocusNode();
  final _containersFocusNode = FocusNode();
  final _itemsFocusNode = FocusNode();

  // 键盘状态
  bool _poKeyboardVisible = false;
  bool _shipmentKeyboardVisible = false;
  bool _datetimeKeyboardVisible = false;
  bool _carrierKeyboardVisible = false;
  bool _proKeyboardVisible = false;
  bool _bolKeyboardVisible = false;
  bool _sealKeyboardVisible = false;
  bool _trailerKeyboardVisible = false;
  bool _scacKeyboardVisible = false;
  bool _containersKeyboardVisible = false;
  bool _itemsKeyboardVisible = false;

  String? _currentFocusField;
  late double _fontScale;
  bool _isDatePickerShowing = false; // 日期选择器显示状态标记

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    // 初始化数据
    final dataMap = widget.jsonData['data'] as Map<String, dynamic>;
    _checkinobj = Checkinobj.fromJson(dataMap);
    id = _checkinobj?.id;
    order = _checkinobj?.order;
    warehouse = _checkinobj?.warehouse;

    _poController.text = _checkinobj?.orderInfo?.orderNumber ?? '';
    _shipmentController.text = _checkinobj?.shipmentCode ?? '';
    _datetimeController.text = _checkinobj?.checkinTime ?? '';
    _carrierController.text = _checkinobj?.carrier ?? '';
    _proController.text = _checkinobj?.proNumber ?? '';
    _bolController.text = _checkinobj?.bolNumber ?? '';
    _sealController.text = _checkinobj?.sealNumber ?? '';
    _trailerController.text = _checkinobj?.trailerNumber ?? '';
    _scacController.text = _checkinobj?.scac ?? '';
    _containersController.text = _checkinobj?.containers != null ? _checkinobj!.containers!.toString() : '';
    _itemsController.text = _checkinobj?.items != null ? _checkinobj!.items!.toString() : '';

    if (_shipmentController.text.isEmpty) {
      _hasShipmentCode = false;
    }

    _initFocusNodeListeners();
  }

  void _initFocusNodeListeners() {
    _poFocusNode.addListener(() => _handleFocusChange('po', _poFocusNode));
    _shipmentFocusNode.addListener(() => _handleFocusChange('shipment', _shipmentFocusNode));
    _carrierFocusNode.addListener(() => _handleFocusChange('carrier', _carrierFocusNode));
    _proFocusNode.addListener(() => _handleFocusChange('pro', _proFocusNode));
    _bolFocusNode.addListener(() => _handleFocusChange('bol', _bolFocusNode));
    _sealFocusNode.addListener(() => _handleFocusChange('seal', _sealFocusNode));
    _trailerFocusNode.addListener(() => _handleFocusChange('trailer', _trailerFocusNode));
    _scacFocusNode.addListener(() => _handleFocusChange('scac', _scacFocusNode));
    _containersFocusNode.addListener(() => _handleFocusChange('containers', _containersFocusNode));
    _itemsFocusNode.addListener(() => _handleFocusChange('items', _itemsFocusNode));

    // 单独处理Datetime焦点
    _datetimeFocusNode.addListener(() {
      if (_datetimeFocusNode.hasFocus && !_isDatePickerShowing) {
        _setCurrentFocusField('datetime');
        _openDateTimePicker();
      } else if (!_datetimeFocusNode.hasFocus) {
        _currentFocusField = null;
      }
    });
  }

  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus && field != 'datetime') {
      _setCurrentFocusField(field);
      _showKeyboardForField(field);
    } else if (!node.hasFocus && field != 'datetime' && _currentFocusField == field) {
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  void _setCurrentFocusField(String field) {
    if (_currentFocusField != null && _currentFocusField != field) {
      if (_currentFocusField != 'datetime') {
        _hideKeyboardForField(_currentFocusField!);
      }
    }
    setState(() {
      _currentFocusField = field;
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    
    // 释放资源
    _poController.dispose();
    _shipmentController.dispose();
    _datetimeController.dispose();
    _carrierController.dispose();
    _proController.dispose();
    _bolController.dispose();
    _sealController.dispose();
    _trailerController.dispose();
    _scacController.dispose();
    _containersController.dispose();
    _itemsController.dispose();

    _poFocusNode.dispose();
    _shipmentFocusNode.dispose();
    _datetimeFocusNode.dispose();
    _carrierFocusNode.dispose();
    _proFocusNode.dispose();
    _bolFocusNode.dispose();
    _sealFocusNode.dispose();
    _trailerFocusNode.dispose();
    _scacFocusNode.dispose();
    _containersFocusNode.dispose();
    _itemsFocusNode.dispose();
    
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  void _resetAllKeyboards() {
    setState(() {
      _poKeyboardVisible = false;
      _shipmentKeyboardVisible = false;
      _datetimeKeyboardVisible = false;
      _carrierKeyboardVisible = false;
      _proKeyboardVisible = false;
      _bolKeyboardVisible = false;
      _sealKeyboardVisible = false;
      _trailerKeyboardVisible = false;
      _scacKeyboardVisible = false;
      _containersKeyboardVisible = false;
      _itemsKeyboardVisible = false;
      _currentFocusField = null;
      _isDatePickerShowing = false;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  void _showKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.show');
    } catch (e) {
      print('显示键盘失败: $e');
    }
  }

  void _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
    }
  }

  void _showKeyboardForField(String field) {
    setState(() {
      _updateKeyboardState(field, true);
    });
    _showKeyboard();
  }

  void _hideKeyboardForField(String field) {
    setState(() {
      _updateKeyboardState(field, false);
    });
    _hideKeyboard();
  }

  void _toggleKeyboardForField(String field) {
    if (field == 'datetime') {
      if (!_isDatePickerShowing) {
        _openDateTimePicker();
      }
      return;
    }
    
    bool currentState = _getKeyboardState(field);
    if (currentState) {
      _hideKeyboardForField(field);
      FocusScope.of(context).unfocus();
    } else {
      _focusOnField(field);
      _showKeyboardForField(field);
    }
  }

  void _focusOnField(String field) {
    FocusScope.of(context).unfocus();
    Future.delayed(const Duration(milliseconds: 100), () {
      switch (field) {
        case 'po':
          FocusScope.of(context).requestFocus(_poFocusNode);
          break;
        case 'shipment':
          FocusScope.of(context).requestFocus(_shipmentFocusNode);
          break;
        case 'datetime':
          FocusScope.of(context).requestFocus(_datetimeFocusNode);
          break;
        case 'carrier':
          FocusScope.of(context).requestFocus(_carrierFocusNode);
          break;
        case 'pro':
          FocusScope.of(context).requestFocus(_proFocusNode);
          break;
        case 'bol':
          FocusScope.of(context).requestFocus(_bolFocusNode);
          break;
        case 'seal':
          FocusScope.of(context).requestFocus(_sealFocusNode);
          break;
        case 'trailer':
          FocusScope.of(context).requestFocus(_trailerFocusNode);
          break;
        case 'scac':
          FocusScope.of(context).requestFocus(_scacFocusNode);
          break;
        case 'containers':
          FocusScope.of(context).requestFocus(_containersFocusNode);
          break;
        case 'items':
          FocusScope.of(context).requestFocus(_itemsFocusNode);
          break;
      }
    });
  }

  bool _getKeyboardState(String field) {
    switch (field) {
      case 'po':
        return _poKeyboardVisible;
      case 'shipment':
        return _shipmentKeyboardVisible;
      case 'datetime':
        return _datetimeKeyboardVisible;
      case 'carrier':
        return _carrierKeyboardVisible;
      case 'pro':
        return _proKeyboardVisible;
      case 'bol':
        return _bolKeyboardVisible;
      case 'seal':
        return _sealKeyboardVisible;
      case 'trailer':
        return _trailerKeyboardVisible;
      case 'scac':
        return _scacKeyboardVisible;
      case 'containers':
        return _containersKeyboardVisible;
      case 'items':
        return _itemsKeyboardVisible;
      default:
        return false;
    }
  }

  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'po':
          _poKeyboardVisible = visible;
          break;
        case 'shipment':
          _shipmentKeyboardVisible = visible;
          break;
        case 'datetime':
          _datetimeKeyboardVisible = visible;
          break;
        case 'carrier':
          _carrierKeyboardVisible = visible;
          break;
        case 'pro':
          _proKeyboardVisible = visible;
          break;
        case 'bol':
          _bolKeyboardVisible = visible;
          break;
        case 'seal':
          _sealKeyboardVisible = visible;
          break;
        case 'trailer':
          _trailerKeyboardVisible = visible;
          break;
        case 'scac':
          _scacKeyboardVisible = visible;
          break;
        case 'containers':
          _containersKeyboardVisible = visible;
          break;
        case 'items':
          _itemsKeyboardVisible = visible;
          break;
      }
    });
  }

  void _openDateTimePicker() {
    setState(() {
      _isDatePickerShowing = true;
    });

    FocusScope.of(context).unfocus();
    _hideKeyboard();

    DateTime initialDate = DateTime.now();
    try {
      if (_datetimeController.text.isNotEmpty) {
        initialDate = DateFormat('yyyy-MM-dd HH:mm:ss').parse(_datetimeController.text);
      }
    } catch (e) {
      initialDate = DateTime.now();
    }

    if (mounted) {
      DatePicker.showDateTimePicker(
        context,
        showTitleActions: true,
        minTime: DateTime(2000, 1, 1),
        maxTime: DateTime(2100, 12, 31),
        onChanged: (date) {},
        onConfirm: (date) {
          if (mounted) {
            setState(() {
              _datetimeController.text = DateFormat('yyyy-MM-dd HH:mm:ss').format(date);
              _isDatePickerShowing = false;
              _datetimeFocusNode.unfocus();
            });
          }
        },
        onCancel: () {
          if (mounted) {
            setState(() {
              _isDatePickerShowing = false;
              _datetimeFocusNode.unfocus();
            });
          }
        },
        currentTime: initialDate,
        locale: LocaleType.en,
      );
    }
  }

  Future<void> _selectDate(BuildContext context) async {
    setState(() {
      _datetimeController.text = DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()).toString();
    });
  }

  TextStyle get _labelStyle {
    return TextStyle(
      fontSize: 13 * _fontScale,
      fontWeight: FontWeight.normal,
    );
  }

  TextStyle get _inputTextStyle {
    return TextStyle(
      fontSize: 12 * _fontScale,
    );
  }

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    final isSmallScreen = mediaQuery.size.width < 360;
    final textScaleFactor = isSmallScreen ? 0.85 : 1.0;
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    
    return MediaQuery(
      data: mediaQuery.copyWith(
        textScaler: TextScaler.linear(textScaleFactor),
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text('Checking Detail', style: TextStyle(fontSize: 18 * _fontScale)),
          automaticallyImplyLeading: false,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/inbound/checkin'),
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.home, color: Colors.white),
              onPressed: () => Navigator.pushNamed(context, '/home'),
            ),
          ],
          backgroundColor: const Color(0xFF008363)
        ),
        body: GestureDetector(
          onTap: () {
            _resetAllKeyboards();
          },
          behavior: HitTestBehavior.opaque,
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: EdgeInsets.symmetric(
                    horizontal: isSmallScreen ? 16 : 32,
                    vertical: isSmallScreen ? 16 : 32
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildInputRow(
                        label: 'PO Number:',
                        controller: _poController,
                        focusNode: _poFocusNode,
                        field: 'po',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'Shipment:',
                        controller: _shipmentController,
                        focusNode: _shipmentFocusNode,
                        field: 'shipment',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildDateTimeRow(isSmallScreen),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'Carrier:',
                        controller: _carrierController,
                        focusNode: _carrierFocusNode,
                        field: 'carrier',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'PRO:',
                        controller: _proController,
                        focusNode: _proFocusNode,
                        field: 'pro',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'BOL:',
                        controller: _bolController,
                        focusNode: _bolFocusNode,
                        field: 'bol',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'Seal#:',
                        controller: _sealController,
                        focusNode: _sealFocusNode,
                        field: 'seal',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'Trailer#:',
                        controller: _trailerController,
                        focusNode: _trailerFocusNode,
                        field: 'trailer',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'SCAC:',
                        controller: _scacController,
                        focusNode: _scacFocusNode,
                        field: 'scac',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'Containers:',
                        controller: _containersController,
                        focusNode: _containersFocusNode,
                        field: 'containers',
                        isSmallScreen: isSmallScreen,
                      ),
                      const SizedBox(height: 12),
                      _buildInputRow(
                        label: 'Items:',
                        controller: _itemsController,
                        focusNode: _itemsFocusNode,
                        field: 'items',
                        isSmallScreen: isSmallScreen,
                      ),
                    ],
                  ),
                ),
              ),
              
              Container(
                padding: EdgeInsets.symmetric(vertical: isSmallScreen ? 16 : 32),
                width: isSmallScreen ? 180 : 240,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFF008363),
                    padding: const EdgeInsets.symmetric(vertical: 12),
                  ),
                  onPressed: !_isLoading ? () => _handleSubmitted() : null,
                  child: _isLoading 
                    ? const SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.white,
                        ),
                      )
                    : const Text('OK', style: TextStyle(color: Colors.white)),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInputRow({
    required String label,
    required TextEditingController controller,
    required FocusNode focusNode,
    required String field,
    required bool isSmallScreen,
  }) {
    return SizedBox(
      height: isSmallScreen ? 28 : 30,
      child: Row(
        children: [
          SizedBox(
            width: isSmallScreen ? 80 : 100,
            child: Text(label, style: _labelStyle),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: TextField(
              readOnly: _isReadOnly,
              controller: controller,
              focusNode: focusNode,
              autofocus: false,
              decoration: InputDecoration(
                border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
                contentPadding: EdgeInsets.symmetric(
                  vertical: isSmallScreen ? 6 : 8,
                  horizontal: 10,
                ),
                suffixIcon: IconButton(
                  icon: Icon(
                    _getKeyboardState(field) ? Icons.keyboard_hide : Icons.keyboard,
                    color: const Color(0xFF008363),
                    size: isSmallScreen ? 18 : 20,
                  ),
                  onPressed: () => _toggleKeyboardForField(field),
                  splashRadius: 20,
                  padding: const EdgeInsets.all(4),
                  constraints: const BoxConstraints.tightFor(width: 36, height: 36),
                ),
              ),
              style: _inputTextStyle,
              onTap: () {
                if (controller.text.isNotEmpty) {
                  controller.selection = TextSelection(
                    baseOffset: 0,
                    extentOffset: controller.text.length,
                  );
                }
                _focusOnField(field);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDateTimeRow(bool isSmallScreen) {
    return SizedBox(
      height: isSmallScreen ? 28 : 30,
      child: Row(
        children: [
          SizedBox(
            width: isSmallScreen ? 80 : 100,
            child: Text('Datetime:', style: _labelStyle),
          ),
          const SizedBox(width: 8),
          Expanded(
            child: TextField(
              readOnly: _isReadOnly,
              controller: _datetimeController,
              focusNode: _datetimeFocusNode,
              autofocus: false,
              decoration: InputDecoration(
                border: const OutlineInputBorder(borderRadius: BorderRadius.zero),
                contentPadding: EdgeInsets.symmetric(
                  vertical: isSmallScreen ? 6 : 8,
                  horizontal: 10,
                ),
                suffixIcon: IconButton(
                  icon: Icon(
                    Icons.calendar_today,
                    color: const Color(0xFF008363),
                    size: isSmallScreen ? 18 : 20,
                  ),
                  onPressed: () => _openDateTimePicker(),
                  splashRadius: 20,
                  padding: const EdgeInsets.all(4),
                  constraints: const BoxConstraints.tightFor(width: 36, height: 36),
                ),
              ),
              style: _inputTextStyle,
              onTap: () {
                _openDateTimePicker();
              },
            ),
          ),
          SizedBox(
            width: isSmallScreen ? 40 : 48,
            height: isSmallScreen ? 28 : 30,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF008363),
                padding: EdgeInsets.zero,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(0),
                ),
              ),
              onPressed: () => _selectDate(context), 
              child: const Text('NOW', style: TextStyle(fontSize: 10, color: Colors.white)),
            ),
          ),
        ],
      ),
    );
  }

  Future<Map<String, dynamic>> _fetchCheckinDetails() async {
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null) {
      throw Exception('The session has expired, Please log in again.');
    }
    
    try {
      http.Response response;
      var apiUrl = ApiService.baseURL + ApiService.upsertCheckin;
      
      if (_hasShipmentCode) {
        final requestBody = {
          "id": id.toString(),
          "order": order.toString(),
          "order_number": _poController.text,
          "shipment_code": _shipmentController.text,
          "carrier": _carrierController.text,
          "pro_number": _proController.text,
          "bol_number": _bolController.text,
          "seal_number": _sealController.text,
          "trailer_number": _trailerController.text,
          "scac": _scacController.text,
          "checkin_time": _datetimeController.text,
          "warehouse": warehouseId
        };
        
        response = await http.post(
          Uri.parse(apiUrl),
          body: jsonEncode(requestBody),
          headers: {
            'Authorization': 'JWT $accessToken',
            'x-warehouse-id': '$warehouseId',
            'x-timezone': 'America/Los_Angeles',
            'Content-Type':'application/json',
            'X-Client-Type':'app'
          },
        );
      } else {
        final requestBody = {
          "order": order.toString(),
          "order_number": _poController.text,
          "shipment_code": _shipmentController.text,
          "carrier": _carrierController.text,
          "pro_number": _proController.text,
          "bol_number": _bolController.text,
          "seal_number": _sealController.text,
          "trailer_number": _trailerController.text,
          "scac": _scacController.text,
          "checkin_time": _datetimeController.text,
          "warehouse": warehouseId
        };
        
        response = await http.post(
          Uri.parse(apiUrl),
          body: jsonEncode(requestBody),
          headers: {
            'Authorization': 'JWT $accessToken',
            'x-warehouse-id': '$warehouseId',
            'x-timezone': 'America/Los_Angeles',
            'Content-Type':'application/json',
            'X-Client-Type':'app'
          },
        );
      }
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if (jsonData['code'] == 401) {
          AuthService().logout(context);
          throw Exception('Session expired, please log in again.');
        } else {
          throw Exception('${jsonData['msg']}');
        }
      } else {
        throw Exception('${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }

  void _handleSubmitted() async {
    if (_isLoading) return;
    _resetAllKeyboards(); 
    setState(() => _isLoading = true);
    setState(() => _isReadOnly = true);
    
    try {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(child: CircularProgressIndicator()),
      );

      Map<String, dynamic> responseData = await _fetchCheckinDetails();
      if(responseData['code'] == 2000 && mounted){
        Navigator.pop(context);
        MessageBox.showMessageBox(context,responseData['msg'],isError:false);
        Navigator.pushNamed(context, '/inbound/checkin');
      }
    } catch (e) {
      if (mounted) {
        Navigator.pop(context);
        MessageBox.showMessageBox(context,e,isError:true);
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
        setState(() => _isReadOnly = false);
      }
    }
  }
}
    